#!/usr/bin/python

# hostbuilder - Tools for DNS zonefile administration
# Copyright (c) 2010 Crown copyright
# 
# This file is part of hostbuilder.
# 
# hostbuilder is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# hostbuilder is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with hostbuilder.  If not, see <http://www.gnu.org/licenses/>.


import sys
from time import localtime, strftime, time

import dns.resolver


def get_serial(zone):
    for rdata in dns.resolver.query(zone, 'SOA'):
        return rdata.serial


def increment_serial(serial):
    new_serial = int(strftime('%Y%m%d00', localtime(time())))
    if new_serial <= serial:
        new_serial = serial + 1
    return new_serial


if __name__ == '__main__':
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-i', '--increment', help="Increment serial number", action="store_true")

    options, args = parser.parse_args()

    if len(args) == 0:
        parser.error("No zone provided to query.")
    elif len(args) > 1:
        parser.error("Cannot query more than one zone.")

    try:
        serial = get_serial(args[0])
        if options.increment:
            serial = increment_serial(serial)
        print serial
    except dns.resolver.NoAnswer:
        print >>sys.stderr, "No answer from nameserver."
        sys.exit(1)

